package com.it.productservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.productservice.common.Result;
import com.it.productservice.entity.Product;
import com.it.productservice.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private ProductService productService;

    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable Integer id) {
         Product product = productService.getById(id);
         if (product != null) {
             return Result.success(product);
         } else {
             return Result.failed("产品不存在");
         }
    }
    
    @GetMapping("/list")
    public Result<List<Product>> getAllProducts() {
        List<Product> products = productService.list();
        return Result.success(products);
    }
    
    @GetMapping("/page")
    public Result<Page<Product>> getProductsByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Product> page = new Page<>(current, size);
        Page<Product> productPage = productService.page(page);
        return Result.success(productPage);
    }
    
    @GetMapping("/type/{type}")
    public Result<List<Product>> getProductsByType(@PathVariable String type) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        List<Product> products = productService.list(queryWrapper);
        return Result.success(products);
    }
    
    @PostMapping
    public Result<Product> addProduct(@RequestBody Product product) {
        boolean success = productService.save(product);
        if (success) {
            return Result.success("添加成功", product);
        } else {
            return Result.failed("添加失败");
        }
    }
    
    @PutMapping("/{id}")
    public Result<Void> updateProduct(@PathVariable Integer id, @RequestBody Product product) {
        product.setId(id);
        boolean success = productService.updateById(product);
        if (success) {
            return Result.success("更新成功", null);
        } else {
            return Result.failed("更新失败，产品不存在");
        }
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> deleteProduct(@PathVariable Integer id) {
        boolean success = productService.removeById(id);
        if (success) {
            return Result.success("删除成功", null);
        } else {
            return Result.failed("删除失败，产品不存在");
        }
    }
}
